<template>
  <view class="app-layout">
    <app-header title="改价格" />
    <view class="app-main">
      <view class="goods-container">
        <view class="goods-title">
          <text>批量设置：</text>
          <view class="goods-title-btn">
            <view class="order-btn" @click="handelOperate('0')">批量改价</view>
            <view class="order-btn" @click="handelOperate('1')">批量加价</view>
            <view class="order-btn" @click="handelOperate('2')">批量减价</view>
          </view>
        </view>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%;">
            <view class="form-container">
              <uni-table border :loading="loading" stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th width="50" align="left">商品</uni-th>
                  <uni-th width="100" align="left">商品名称</uni-th>
                  <uni-th width="150" align="left">规格</uni-th>
                  <uni-th width="150" align="left"><text class="start">* </text>零售价（元）</uni-th>
                  <uni-th width="150" align="left">市场价（元）</uni-th>
                  <uni-th align="left" width="150">成本价（元）</uni-th>
                </uni-tr>
                <uni-tr v-for="(row, rIndex) in tableData" :key="rIndex">
                  <uni-td>
                    <image :src="row.mainImage" mode="widthFix" style="height: 32px;width:32px"></image>
                  </uni-td>
                  <uni-td>
                    <text>{{row.name}}</text>
                  </uni-td>
                  <uni-td>
                    <text>{{row.specComboDesc}}</text>
                  </uni-td>
                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.retailPrice"></uni-easyinput>
                  </uni-td>
                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.marketPrice"></uni-easyinput>
                  </uni-td>
                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="digit" clearable v-model="row.costPrice"> </uni-easyinput>
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>
          </scroll-view>
        </view>
        <customPopup v-if="showPopup" :showPopup="showPopup" :typePopup="typePopup" :titPopup="titPopup"
          :infoPopup="infoPopup" @cancelPopup="cancelPopup" @surePopup="surePopup" />
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import
  customPopup
  from '@/components/customPopup/index.vue';
  import {
    pricePage,
    updatePrice
  } from '@/requests/apis/products'

  import
  addPopup
  from '@/components/addPopup/index.vue'
  let tableData = ref([{

  }])
  let loading = ref(true)
  let showPopup = ref(false);
  let titPopup = ref("");
  let typePopup = ref("");
  let infoPopup = ref("")
  onLoad(async (e) => {
    loading.value = true
    console.log(e, 'eeeeee')
    if (e.spuIds) {
      let spuIds = e.spuIds.split(",")
      let res = await pricePage({
        spuIds,
        page: 1,
        limit: 999
      })
      console.log(res.Result)
      tableData.value = (res.Result.records || []).map(item => ({
        ...item,
        retailPrice: item.retailPrice === 0 ?
          "0" : item.retailPrice ?
          String(item.retailPrice) : "",
        marketPrice: item.marketPrice === 0 ?
          "0" : item.marketPrice ?
          String(item.marketPrice) : "",
        costPrice: item.costPrice === 0 ?
          "0" : item.costPrice ?
          String(item.costPrice) : ""
      }));

      loading.value = false
    }
  })
  const handelOperate = (type) => {
    showPopup.value = true;
    if (type == '0') {
      titPopup.value = "批量改价"
      infoPopup.value = '请输入商品改价后金额'
    } else if (type == '1') {
      titPopup.value = "批量加价"
      infoPopup.value = '请输入商品加价金额'
    } else {
      titPopup.value = "批量减价"
      infoPopup.value = '请输入商品减价金额'
    }
    typePopup.value = type
  }
  // 弹窗取消
  const cancelPopup = () => {
    showPopup.value = false;
  };

  // 弹窗确认
  const surePopup = (type, modelValue) => {
    let _modelValue = Number(modelValue);
    showPopup.value = false;

    const fixDecimal = (num) => {
      return Math.round(num * 100) / 100; // 四舍五入到两位小数
    };

    if (type === "0") {
      tableData.value.forEach((row) => {
        row.retailPrice = fixDecimal(_modelValue);
        row.marketPrice = fixDecimal(_modelValue);
        row.costPrice = fixDecimal(_modelValue);
      });
    } else if (type === "1") {
      tableData.value.forEach((row) => {
        row.retailPrice = fixDecimal(Number(row.retailPrice) + _modelValue);
        row.marketPrice = fixDecimal(Number(row.marketPrice) + _modelValue);
        row.costPrice = fixDecimal(Number(row.costPrice) + _modelValue);
      });
    } else {
      tableData.value.forEach((row) => {
        row.retailPrice = fixDecimal(Number(row.retailPrice) - _modelValue);
        row.marketPrice = fixDecimal(Number(row.marketPrice) - _modelValue);
        row.costPrice = fixDecimal(Number(row.costPrice) - _modelValue);
      });
    }
  };
  const submit = async () => {
    const priceReg = /^\d+(\.\d{1,2})?$/;

    for (let i = 0; i < tableData.value.length; i++) {
      const item = tableData.value[i];
      const rowNum = i + 1;
      const retailPriceStr = String(item.retailPrice).trim();
      console.log(retailPriceStr, 'retailPriceStr')
      // 1. 校验零售价：非空 + 是有效数字格式
      if (!retailPriceStr || isNaN(Number(retailPriceStr))) {
        uni.showToast({
          title: `请输入零售价`,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 2. 校验零售价：非负（不能为负数）
      const retailPriceNum = Number(retailPriceStr);

      // 3. 校验零售价：整数或两位小数（用正则匹配格式）
      if (!priceReg.test(retailPriceStr)) {
        uni.showToast({
          title: `零售价必须为整数或两位小数`,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 5. 类型转换：确保提交给接口的是数字类型
      item.retailPrice = Number(retailPriceNum);

      // 6. 市场价/成本价
      if (item.marketPrice !== null && item.marketPrice !== '' && !isNaN(Number(item.marketPrice))) {
        const marketPriceNum = Number(item.marketPrice);
        if (marketPriceNum < 0) {
          uni.showToast({
            title: `市场价必须为整数或两位小数`,
            icon: 'none'
          });
          return;
        }
        item.marketPrice = Number(marketPriceNum);
      } else {
        item.marketPrice = null
      }
      if (item.costPrice !== null && item.costPrice !== '' && !isNaN(Number(item.costPrice))) {
        const costPriceNum = Number(item.costPrice);
        if (costPriceNum < 0) {
          uni.showToast({
            title: `成本价必须为整数或两位小数`,
            icon: 'none'
          });
          return;
        }
        item.costPrice = Number(costPriceNum);
      } else {
        item.costPrice = null
      }
    }
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    try {
      const res = await updatePrice({
        priceList: tableData.value
      })
      console.log(res, 'resres')
      uni.hideLoading()
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 800)
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  :deep(.u-input) {
    background: #fff !important;
  }

  .form-container {
    padding: 0 20px;
    box-sizing: border-box;
  }

  .goods-container {
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    width: 100%;

    .goods-title {
      display: flex;
      padding: 20px 20px;
      box-sizing: border-box;
      align-items: center;

      text {
        font-weight: 500;
        font-size: 14px;
        color: #333333;
      }

      .goods-title-btn {
        display: flex;

        .order-btn {
          border-radius: 8px;
          border: 1px solid #0f90fd;
          color: #0f90fd;
          font-weight: 500;
          font-size: 14px;
          padding: 6px 20px;
          box-sizing: border-box;
          margin-right: 10px;
        }
      }
    }
  }
</style>
